package com.lau.xml;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * Created by liutf on 2016/5/30.
 */
public class MyDom4j {

    public final static String ROOT_NODE_KEY = "ROOT_NODE_KEY";
    public final static String SEQUENCE_KEY = "sequence";
    public final static String SUB_NODE_KEY = "SUB_NODE_KEY";
    public final static String ROOT_NODE_INSER_VAL = "SIMM-PROVISIONING-REQUEST";
    public final static String SUB_NODE__VAL = "SIMM-SUBSCRIBERS";


    public static void createDemo() throws Exception{

        Document document = DocumentHelper.createDocument();

        Element root = document.addElement("SIMM-INQUIRING-REQUEST")
                .addAttribute("version", "1.0");

        Element entries = root.addElement("SIMM-SUBSCRIBERS")
                .addAttribute("entries", "2");

        entries.addElement("SUBSCRIBER-DATA")
                .addElement("MSISDN-H")
                .addAttribute("value","111");

        entries.addElement("SUBSCRIBER-DATA")
                .addElement("MSISDN-H").
                addAttribute("value","222");

        XMLWriter xmlWriter = new XMLWriter(System.out, OutputFormat.createPrettyPrint());
        xmlWriter.write(document);
    }


    public static String createRespXML() throws Exception{
//        <SIMM-PROVISIONING-RESULT version="1.0" date="09/19/2015 14:01:00" sequence="1">
//        <SUMMARY successful="1" failed="2"/>
//        <SUBSCRIBER IMSI-H="460011234567890" status="0">
//           <NETWORK MSISDN-F=” 85255697100”  status=”0”/>
//        </SUBSCIBER>
//
//        <SUBSCRIBER IMSI-H ="3104101234567891" status="1001"/>
//        </SIMM-PROVISIONING-RESULT>

        Document document = DocumentHelper.createDocument();

        Element root = document.addElement("SIMM-PROVISIONING-RESULT")
                .addAttribute("version", "1.0")
                .addAttribute("date", "09/19/2015 14:01:00")
                .addAttribute("sequence", "1");

        root.addElement("SUMMARY")
                .addAttribute("successful","1")
                .addAttribute("failed","2");

        Element element = root.addElement("SUBSCRIBER")
                .addAttribute("IMSI-H", "460011234567890")
                .addAttribute("status", "0");
        element.addElement("NETWORK")
                .addAttribute("MSISDN-F","85255697100")
                .addAttribute("status","0");


        root.addElement("SUBSCRIBER")
                .addAttribute("IMSI-H","3104101234567891")
                .addAttribute("status","1001");

        XMLWriter xmlWriter = new XMLWriter(System.out, OutputFormat.createPrettyPrint());
        xmlWriter.write(document);

        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setEncoding("UTF-8");

        StringWriter stringWriter = new StringWriter();
        XMLWriter writer = new XMLWriter(stringWriter,outputFormat);
        writer.write(document);
        writer.close();

        return stringWriter.toString();
    }


    public static void createByUsers(String[] userNames) throws Exception{

        Document document = DocumentHelper.createDocument();

        Element root = document.addElement("SIMM-INQUIRING-REQUEST")
                .addAttribute("version", "1.0");

        Element entries = root.addElement("SIMM-SUBSCRIBERS")
                .addAttribute("entries", "2");

        for (String userName : userNames) {
//            entries.addElement("SUBSCRIBER-DATA")
//                    .addElement("MSISDN-H").
//                    addAttribute("value",userName);

            Element element = entries.addElement("SUBSCRIBER-DATA")
                    .addElement("MSISDN-H");
            element.addAttribute("value",userName);
            element.addAttribute("name","aaa");

        }

        XMLWriter xmlWriter = new XMLWriter(System.out, OutputFormat.createPrettyPrint());
        xmlWriter.write(document);
    }

    /**
     *  创建报文
     * @param inMap
     * @param dataList
     * @return
     * @throws Exception
     */
    public static String createSubProvInsert(Map inMap,List<List> dataList) throws Exception{

//        boolean verifyResult = verifyParaMap(inMap);

        Document document = DocumentHelper.createDocument();

        Element root = document.addElement("SIMM-PROVISIONING-REQUEST")
                .addAttribute("version", "1.0")
                .addAttribute("date",getSysDate())
                .addAttribute("sequence","1");

        Element entries = root.addElement("SIMM-SUBSCRIBERS")
                .addAttribute("entries", dataList.size() + "");

        for (List<Map> list : dataList) {
            Element userNode = entries.addElement("SUBSCRIBER-DATA");
            list.stream().filter(map -> map.containsKey("nodeName")).forEach(map -> {
                Element userSubNode = userNode.addElement((String) map.get("nodeName"));
                for (Object obj : map.keySet()) {
                    String keyName = (String) obj;
                    if (!StringUtils.equals("nodeName", keyName)) {
                        userSubNode.addAttribute(keyName, map.get(keyName) + "");
                    }
                }
            });
        }

        //打印输出
//        XMLWriter xmlWriterPrinter = new XMLWriter(System.out,OutputFormat.createPrettyPrint());
//        xmlWriterPrinter.write(document);

        //输入指定文件
//        XMLWriter XMLWriter = new XMLWriter(new FileWriter("D;\\SubProv.xml"));

        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setEncoding("UTF-8");

        StringWriter stringWriter = new StringWriter();
        XMLWriter XMLWriter = new XMLWriter(stringWriter,outputFormat);
        XMLWriter.write(document);
        XMLWriter.close();
        System.out.println(stringWriter.toString());

        return stringWriter.toString();

    }

    public static void parseXML() throws Exception {

        String xmlStr = createRespXML();

        SAXReader reader = new SAXReader();
        InputStream inputStream = new ByteArrayInputStream(xmlStr.getBytes());
        Document document = reader.read(inputStream);

        Element rootElement = document.getRootElement();
        String rootName = rootElement.getName();
        String version1 = rootElement.attributeValue("version");
        String date = rootElement.attributeValue("date");
        String sequence = rootElement.attributeValue("sequence");

        List<Node> list = document.selectNodes("/" + rootName + "/SUMMARY");
        for (Node node : list) {
            String nodeName = node.getName();
            String successful = node.valueOf("@successful");
            String failed = node.valueOf("@failed");
            System.out.println(nodeName);
            System.out.println(successful);
            System.out.println(failed);
        }

        List<Node> subscriberList = document.selectNodes("/" + rootName + "/SUBSCRIBER");
        for (Node node : subscriberList) {
            String nodeName = node.getName();
            String IMSI = node.valueOf("@IMSI-H");
            String status = node.valueOf("@status");
            System.out.println(nodeName);
            System.out.println(IMSI);
            System.out.println(status);

            Node singleNode = node.selectSingleNode("NETWORK");
            if (singleNode != null) {
                System.out.println(singleNode.getName());
                System.out.println(singleNode.valueOf("@MSISDN-F"));
            }

        }

    }





    private static boolean verifyParaMap(Map inMap) {
        boolean result = true;
        String rootNodeKey =  inMap.containsKey(MyDom4j.ROOT_NODE_KEY)
                ? inMap.get(MyDom4j.ROOT_NODE_KEY) + ""  : "";
        String sequence =  inMap.containsKey(MyDom4j.SEQUENCE_KEY)
                ? inMap.get(MyDom4j.SEQUENCE_KEY) + ""  : "";
        String subNodeKey =  inMap.containsKey(MyDom4j.SUB_NODE_KEY)
                ? inMap.get(MyDom4j.SUB_NODE_KEY) + ""  : "";


        return result;
    }

    public static String getSysDate(){
        String pattern_MMDDYYYY_HHMMSS = "MM/dd/yyyy hh:mm:ss";
        String pattern_YYYY_MMDD_HHMMSS = "yyyy/MM/dd hh:mm:ss";
        DateTimeFormatter format = DateTimeFormatter.ofPattern(pattern_MMDDYYYY_HHMMSS);
        return LocalDateTime.now().format(format);
    }



    public static void main(String[] args) throws Exception {

//        MyDom4jCreate.createDemo();

//        MyDom4jCreate.createByUsers(new String[]{"111","222","333"});

//        System.out.println(getSysDate()); //outPut : 05/31/2016 10:09:06

//        createRespXML();

         MyDom4j.parseXML();


        /**  MyDom4jCreate.createSubProvInsert

        Map imsi_map = new HashMap<>();
        Map msisdn_map = new HashMap<>();
        Map network_map = new HashMap<>();
        Map scos_map = new HashMap<>();


        imsi_map.put("nodeName","IMSI");
        imsi_map.put("value","460011234567890");

        msisdn_map.put("nodeName","MSISDN");
        msisdn_map.put("value","8617012345671");

        network_map.put("nodeName","NETWORK");
        network_map.put("IMSI-F","4540312345601");
        network_map.put("MSISDN-F","85244123401");
        network_map.put("FCOS","C1");


        List list = new ArrayList<>();
        list.add(imsi_map);
        list.add(msisdn_map);
        list.add(network_map);
        list.add(scos_map);

        List list2 = new ArrayList<>();
        list2.add(imsi_map);
        list2.add(msisdn_map);
        list2.add(network_map);
        list2.add(scos_map);

        List dataList = new ArrayList<>();
        dataList.add(list);
        dataList.add(list2);

        String subProvInsert = MyDom4jCreate.createSubProvInsert(null, dataList);

         **/





    }

}
